package novemberBot.sensor;

import novemberBot.communication.ConnectionManager;
import lejos.nxt.LightSensor;
import lejos.nxt.SensorPort;

/**class that polls the right light sensor and passes the relevant data to the Line checker on the master brick
 * through the RS485 connection manager
 * @author Antoine Lennartz*/
public class LSPoller extends Thread{
	
	/**attached Light Sensor set by Constructor*/
	private LightSensor ls;
	
	/**light level for line*/
	public static int THRESHOLD;
	
	/**state boolean*/
	private boolean onLine=false;
	
	private boolean corrected=false;
	
	private ConnectionManager cm;

	
	public LSPoller(ConnectionManager cm){
		ls = new LightSensor(SensorPort.S3);
		this.cm=cm;
		this.start();
		ls.setFloodlight(true);
		try { Thread.sleep(40);
		} catch (InterruptedException e) {
		}
		THRESHOLD=ls.getNormalizedLightValue()-30;
	}
	
	
	public void run(){
		while(true){
			if(isOnLine()!=onLine){
				onLine =!onLine;
				//Debugger.audibleDebug(400, 200);
				sendInfo();
			}	
		}
	}
	/**sends line cross info to masterBrick
	 * sends 1 if online and 0 if not*/
	private void sendInfo() {
		byte b=0;
		if(onLine) b++;
		cm.passRaw(new byte[]{b}, (byte) 1);	
	}
	
	/**Checks to see if sensorValue-THRESHOLD>60*/
	private boolean isOnLine(){
		if(ls.readNormalizedValue()-THRESHOLD>60 && !corrected){
			THRESHOLD+=60;
			corrected=true;
		}
		return ls.readNormalizedValue()<THRESHOLD;
		
	}
	
	
}
